const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const tokenMiddleware = require('./middleware/tokenMiddleware')
const adminController = require('./controller/AdminController')
const logoController = require('./controller/LogoController')

const adminRouter = require("./router/admin.router");
const pcRouter = require("./router/pc.router");
const {PORT} = require("./config");
const multer = require("multer");
let upload = multer({dest: 'uploads/'})


const app = express()


app.use(cors())

// http请求日志中间件
app.use(morgan('tiny'))

// app.use(虚拟路径,资源目录)
app.use('/uploads/', express.static('./uploads/'))

// 中间件：统一校验token。任何请求路径只要是/api打头,都会经过下面的中间件
app.use('/api', tokenMiddleware)

// 解析表单请求体 application/json
app.use(express.json())

// 解析表单请求体 application/x-www-form-urlencoded，extended: true 允许包含任何数据类型
app.use(express.urlencoded({ extended: true }))

// 后端管理路由
app.use('/api/admin',adminRouter)

// pc端路由
app.use('/api/pc',pcRouter)

// 后台登录接口
app.post('/admin/login', adminController.login)

// 刷新token
app.post('/admin/refreshToken', adminController.refreshToken)

// 获取logo
app.get('/admin/logo', logoController.getLogoInfo)

// 添加Logo图片
app.post('/admin/logoImg',upload.single('logo'),logoController.addLogoImg)

// 修改Logo图片
app.put('/admin/logoImg',logoController.setLogoImg)

// 修改logo标题
app.put('/admin/logoTitle',logoController.setLogoTitle)


// 获取upload目录中所有图片资源
app.get('/admin/getImages', adminController.getImages)

// // 删除指定图片文件
app.delete('/admin/delImages', adminController.delImages)

// // 错误中间件,如参数错误，或sql执行错误
// app.use((err, req, res, next) => {
//   res.json({ code: '00100', msg: err, data: {} })
// })

app.listen(PORT, () => {
  console.log('server is running at port 4000')
})
